<?php
// ------------------------------------------------------------------------------------
// Bestand:       Question
// Versie:        101
// Projekt:       Cursus MasterClass van Eduvision
// Datum:         14-07-2008
// Auteur(s):     Ronald Obbens
// Email(s):      ronaldobbens@gmail.com
// Revisie(s):	 1.1 Vraag wordt toegeveogd, indien een gebruiker ingelogd is word deze aan de gebruiker gekoppeld anders niet 
//
// Beschrijving:  deze controller coordineert het gedrag van de models en gegevens stromen
// ------------------------------------------------------------------------------------
//

require_once('Controller.php');
require_once('DataBase.php');
require_once('MailMessage.php');
require_once('Question.php');
require_once('Mailsender.php');

class questionController extends Controller
{
	/**
	 * Index action
	 * 
	 * default action for the question controller. shows the last 20 questions
	 *
	 */
	public function index()
	{
		$aQuestions = array();
		
		foreach($this->getLastQuestions(20) AS $question)
		{
	  		$aQuestions[] = '<a href="'.DOMAIN_URL.'/question/showitem/' . $question->getId() . '/' . $question->getquestion() . '">' . (string) $question->getQuestion() . '</a>';
		}
		
		parent::assign('questions', $aQuestions);
		parent::render('questionlist.tpl');
	}
	
	/**
	 * gets the defined number of questions order by date
	 *
	 * @param integer $p_iAantal
	 * @return Qrraty with Question Models
	 */
	public function getLastQuestions($p_iAantal)
	{
		$output = DataBase::getInstance()->runDirectQuery("SELECT Id FROM Question WHERE answer is not null ORDER BY Id DESC LIMIT " . $p_iAantal . "");
		$_aQuestionlist = array();
		
		foreach($output->getData() as $question)
		{
			$oQuestion = new Question();
			$oQuestion->setByParentId($question['Id']);
			$_aQuestionlist[] = $oQuestion;
		}
		return $_aQuestionlist;
	}
	
	/**
	 * search through the questions
	 *
	 * @param string $p_sKeywords
	 * @return array with questionid's and the question
	 */
	private function searchQuestions($p_sKeywords)
	{
		$a_QuestionWithAnswer = array();
		
		//split question in keywords
		$_aQuestionChunks = explode(' ',$p_sKeywords);

		//get questions from database
		$output = DataBase::getInstance()->runDirectQuery("SELECT * FROM Question");
	
		//loop through the questions to compare the keywords
		foreach($output->getData() as $_aQuestion)
		{
			$oQuestion = new Question();
			$oQuestion->setByParentId($_aQuestion['id']);
			
			//split the keywords set in the database
			$_aKeywords = explode(' ',$oQuestion->getKeywords());
			
			//count the number of keywords in the database
			$iTotalKeyCount = count($_aKeywords);
			
			//set an hitcounter
			$iHitCount = null;
					
			//loop through the keywords from the question
			foreach($_aQuestionChunks as $s_Chunk)
			{
				//loop throught the keywords from the database
				foreach($_aKeywords as $sKeyword)
				{
					//compare the keywords an if hit increment the hitcounter
					if($sKeyword === $s_Chunk)
					{
						$iHitCount++;
					}
				}
			}
			
			//if al the keywords of the question from the DB are compared
			//check if there are any matching keywords 
			if($iHitCount != null)
			{
				//check if an answer is set
				if($oQuestion->getAnswer()!= null)
				{
					//get the percentage of the keywords in the submitted question that match the keywords
					//$trueperc = round(($iHitCount/$iTotalKeyCount)*100,0);
					
					//set an array row with an array containing the id,queston and percentage
					$a_QuestionWithAnswer[] = $oQuestion;
				}
			}
		}
		
		//if no matching question has been found return false
		if(empty($a_QuestionWithAnswer))
		{
			return false; 
		}
		
		//else return the array with questions
		else
		{
			return $a_QuestionWithAnswer;	
		}
	}

	/**
	 * start the ask question routine
	 *
	 */
	public function ask()
	{
		$_sQuestion = $_POST['question'];
		
		
		$aQuestions = array();		
		if($this->searchQuestions($_sQuestion) != false)
		{
			foreach($this->searchQuestions($_sQuestion) as $Question)
			{
				$aQuestions[] = '<li><a href="'.DOMAIN_URL.'/question/showitem/' . $Question->getId() .'/'. $Question->getQuestion() .'">'.$Question->getQuestion().' </a></li>';
			}
			parent::assign('askedquestion',$_sQuestion);
			parent::assign('questions',$aQuestions);
		 	parent::render('questionlist.tpl');
		}
		else
		{
			$this->nieuw($_sQuestion);
		}
	}
	
	/**
	 * insert new question routine
	 * 
	 * insert in database, chqeck if user has been logged in.
	 * true question will be paired to user, else question is anonimus
	 *
	 */
	public function nieuw($p_sQuestion)
	{
			$_sQuestion = $p_sQuestion;
	
			$DB = DataBase::getInstance();
			$output = $DB->runDirectQuery("INSERT INTO Question (Users_id ,Categories_id ,question ,date) VALUES ('1', '1', '" . $_sQuestion . "', '" . time() . "')");
			
			$oQuestion = new Question();
			$oQuestion->setByParentId($output->getRecordID());
				
			if(!isset($_SESSION['user']))
			{
				parent::assign('firstquestion',$oQuestion->getId());
				parent::render('asked_nologin.tpl');
			}
			else
			{
				$user = new User();
				$user->setByParentId($_SESSION['user']);
				
				$mailMessage = new MailMessage();
				$mailMessage->setSubject('Nieuwe vraag op Askkid.nl.');
				$mailMessage->addRecipient($user->getEmail());
				
				$mailMessage->assign('realname',$user->getRealname());
				$mailMessage->setMessage('mail_newQuestion.tpl');				
		
  				$mailSender = new Mailsender();
  				$mailSender->sendMailMessage($mailMessage);
				
  				$DB->runDirectQuery("UPDATE FROM Question SET userid='". $user->getId() . "' WHERE id = '". $questionIdInDb ."'");
			}
	}
	
	/**
	 * show item with defined id
	 *
	 * @param integer $p_sQuestionId
	 */
	public function showItem($p_sQuestionId)
	{
		$p_sQuestionId = explode('/',$p_sQuestionId);
		
		$question = new Question();
		$question->setByParentId($p_sQuestionId[0]);
		
		parent::assign('question',$question->getQuestion());
		
		$user = new User();
		$user->setByParentId($question->getUserId());
		parent::assign('asker',$user->getRealname());
		parent::assign('answer',$question->getAnswer());
		parent::assign('expert',$question->getAnswerrer());
		parent::render('question.tpl');
		
	}	
}

?>